package com.leo.chapter15;

import java.util.concurrent.atomic.AtomicReference;

/**
 *
 * @author xuexiaolei
 * @version 2017年10月20日
 */
public class LinkedNode<E> {
    private static class Node<E>{
        final E item;
        final AtomicReference<Node<E>> next;

        private Node(E item, AtomicReference<Node<E>> next) {
            this.item = item;
            this.next = next;
        }
    }

    private final Node<E> dummy = new Node<>(null, null);//哑节点
    private final AtomicReference<Node<E>> head = new AtomicReference<>(dummy);
    private final AtomicReference<Node<E>> tail = new AtomicReference<>(dummy);

    public boolean put(E item){
        Node<E> newNode = new Node<>(item, null);
        while (true){
            Node<E> curTail = tail.get();
            Node<E> tailNext = curTail.next.get();
            if (curTail == tail.get()){
                if (tailNext != null){
                    //处于中间状态，推进尾节点
                    tail.compareAndSet(curTail, tailNext);
                }else{
                    if (curTail.next.compareAndSet(null, newNode)){
                        tail.compareAndSet(curTail, newNode);
                        return true;
                    }
                }
            }
        }
    }
}
